package com.trkj.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.trkj.dao.jpa.IYzrMedDrawDAO;
import com.trkj.dao.jpa.IYzrMedDrawDetDAO;
import com.trkj.dao.jpa.IYzrMedOutstockDAO;
import com.trkj.dao.jpa.IYzrMedOutstockDetDAO;
import com.trkj.dao.jpa.IYzrMedStockDAO;
import com.trkj.dao.jpa.IYzrMedicineDAO;
import com.trkj.dao.jpa.IYzrPharInstockDAO;
import com.trkj.dao.jpa.IYzrPharInstockDetDAO;
import com.trkj.dao.jpa.IYzrPharStockDAO2;
import com.trkj.dao.jpa.IYzrPharmacyDAO;
import com.trkj.dao.jpa.IYzrStorehouseDAO;
import com.trkj.dao.jpa.IYzrTbstaffDAO;
import com.trkj.pojos.Tbstaff;
import com.trkj.pojos.YzrMedDraw;
import com.trkj.pojos.YzrMedDrawDet;
import com.trkj.pojos.YzrMedOutstock;
import com.trkj.pojos.YzrMedOutstockDet;
import com.trkj.pojos.YzrMedStock;
import com.trkj.pojos.YzrMedicine;
import com.trkj.pojos.YzrPharInstock;
import com.trkj.pojos.YzrPharInstockDet;
import com.trkj.pojos.YzrPharStock;
import com.trkj.pojos.YzrPharmacy;
import com.trkj.pojos.YzrStorehouse;
import com.trkj.vo.YzrMedOutstockVo;
import com.trkj.vo.YzrPharStockVo;

@Service
@Transactional
public class YzrOutStockService {

	@Autowired
	private IYzrMedOutstockDAO yzrMedOutstockDAO;//出库	
	@Autowired
	private IYzrMedOutstockDetDAO yzrMedOutstockDetDAO;//出库详情	
	@Autowired
	private IYzrPharInstockDAO yzrPharInstockDAO;//药房入库	
	@Autowired
	private IYzrPharInstockDetDAO yzrPharInstockDetDAO;//药房入库详情	
	@Autowired
	private IYzrPharStockDAO2 yzrPharStockDAO2;//药房库存
	@Autowired
	private IYzrMedDrawDAO yrMedDrawDAO;//提领单
	@Autowired
	private IYzrMedDrawDetDAO yzrMedDrawDetDAO;//提领详情单
	@Autowired
	private IYzrMedicineDAO yzrMedicineDAO;//药品
	@Autowired
	private IYzrMedStockDAO yzrMedStockDAO;//药库库存
	@Autowired
	private IYzrPharmacyDAO yzrPharmacyDAO;
	@Autowired
	private IYzrStorehouseDAO yzrStorehouseDAO;//仓库	
	@Autowired
	private IYzrTbstaffDAO yzrTbstaffDAO;
	
	/**
	 * 根据出库id查询出库详情信息
	 * @param outstockId
	 * @return
	 */
	public List<YzrMedOutstockDet> queryOutstockByOutId(String outstockId){
		return yzrMedOutstockDetDAO.findDetByOutId(outstockId);
	}
	
	
	/**
	 * 根据出库id查询出库信息
	 * @param outstockId
	 * @return
	 */
	public YzrMedOutstockVo queryOutstockById(String outstockId){
		return outstockPoToVo(yzrMedOutstockDAO.findOne(outstockId));
	}
	
	/**
	 * 分页查询出库信息
	 * @param page
	 * @param rows
	 * @return
	 */
	public Map<String,Object> queryAllOutstock(int page, int rows){
		PageRequest pr = new PageRequest(page - 1, rows);
		List<YzrMedOutstock> list = yzrMedOutstockDAO.findByStock(pr);
		long total = yzrMedOutstockDAO.count();
		Map<String, Object> map = new HashMap<>();
		map.put("total", total);
		map.put("rows", outstockListToVo(list));
		return map;
	}
	private List<YzrMedOutstockVo> outstockListToVo(List<YzrMedOutstock> list){
		if(list == null) return null;
		List<YzrMedOutstockVo> listVo = new ArrayList<>();
		
		for(YzrMedOutstock purchOrder: list){
			YzrMedOutstockVo purchOrderVo = outstockPoToVo(purchOrder);
			listVo.add(purchOrderVo);
		}
		return listVo;
	}
	public YzrMedOutstockVo outstockPoToVo(YzrMedOutstock purchOrder){
		YzrMedOutstockVo purchOrderVo = new YzrMedOutstockVo();
		purchOrderVo.setMedOutstockId(purchOrder.getMedOutstockId());
		purchOrderVo.setMedOutstockKind(purchOrder.getMedOutstockKind());
		purchOrderVo.setMedOutstockMedDrawId(purchOrder.getMedOutstockMedDrawId());
		purchOrderVo.setMedOutstockPerson(purchOrder.getMedOutstockPerson());
		purchOrderVo.setMedOutstockStoreId(purchOrder.getMedOutstockStoreId());
		purchOrderVo.setMedOutstockTime(purchOrder.getMedOutstockTime());
		purchOrderVo.setMedOutstockWhere(purchOrder.getMedOutstockWhere());

		BigDecimal rkr = purchOrder.getMedOutstockPerson();
		String store = purchOrder.getMedOutstockStoreId();
		String phar2 = purchOrder.getMedOutstockWhere();
		
		if(rkr != null){
			Tbstaff staff = yzrTbstaffDAO.findOne(rkr.longValue());
			purchOrderVo.setStaffName(staff!=null? staff.getStaffName():null);
		}
		if(store != null){		
			YzrStorehouse storehouse = yzrStorehouseDAO.findOne(store);	
			purchOrderVo.setStoreName(storehouse != null ? storehouse.getStoreName() : null);
		}
		if(phar2 != null){		
			YzrPharmacy phar = yzrPharmacyDAO.findOne(phar2);	
			purchOrderVo.setPharName(phar != null ? phar.getPharmacyName() : null);
		}

		return purchOrderVo;
	}
	
	
	
	
	
	public Map<String,Object> queryMedByMedName(String medName,int page, int rows){
		PageRequest pr = new PageRequest(page - 1,rows);
		List<YzrPharStock> list = yzrPharStockDAO2.findMedByMedName(medName, pr);
		
		Map<String, Object> map = new HashMap<>();
		
		map.put("total", list.size());
		map.put("rows", pharStoreListToVo(list));
		return map;
	}
	
	
	
	
	/**
	 * 分页查询
	 * @param page
	 * @param rows
	 * @return
	 */
	public Map<String,Object> queryAllByPage(int page, int rows){
		PageRequest pr = new PageRequest(page - 1,rows);
		List<YzrPharStock> list = yzrPharStockDAO2.findAllByPage(pr);
		
		long count = yzrPharStockDAO2.count();
		
		Map<String, Object> map = new HashMap<>();
		
		map.put("total", count);
		map.put("rows", pharStoreListToVo(list));
		return map;
	}
	private List<YzrPharStockVo> pharStoreListToVo(List<YzrPharStock> list){
		if(list == null) return null;
		List<YzrPharStockVo> listVo = new ArrayList<>();
		
		for(YzrPharStock store: list){
			YzrPharStockVo storeVo = pharStorePoToVo(store);
			listVo.add(storeVo);
		}
		return listVo;
	}
	public YzrPharStockVo pharStorePoToVo(YzrPharStock medPurch){
		
		//库存编号，药房编号，药品编号，药品名，批号，类型（中药，西药），规格，单位，单价，数量，售价
		YzrPharStockVo medPurchVo = new YzrPharStockVo();
		medPurchVo.setPharStockId(medPurch.getPharStockId());
		medPurchVo.setPharStockStoreId(medPurch.getPharStockStoreId());
		medPurchVo.setPharStockMedId(medPurch.getPharStockMedId());
		medPurchVo.setPharStockMedName(medPurch.getPharStockMedName());
		medPurchVo.setPharStockBatchnumber(medPurch.getPharStockBatchnumber());
		medPurchVo.setPharStockMedKind(medPurch.getPharStockMedKind());
		medPurchVo.setPharStockGuige(medPurch.getPharStockGuige());
		medPurchVo.setPharStockUnit(medPurch.getPharStockUnit());
		medPurchVo.setPharStockPrice(medPurch.getPharStockPrice());
		medPurchVo.setPharStockMedNumber(medPurch.getPharStockMedNumber());
		medPurchVo.setMaiMoney(medPurch.getMaiMoney());
		
		YzrPharmacy pharName = yzrPharmacyDAO.findOne(medPurch.getPharStockStoreId());
		medPurchVo.setPharName(pharName != null?pharName.getPharmacyName():null);
		
		return medPurchVo;
	}
	
	
	
	
	
	
	
	
	
	
	/**
	 * 提交出库数据
	 * @param drawId
	 * @param kind
	 * @param ckr
	 * @param tlr
	 */
	public void addOutstock(String drawId,String kind,String ckr,String tlr){
		//添加出库和出库详情		
		String year = getNowDate();
		//拼接
		String nameOut = "OS-" + year;	//出库
		String nameOutdet = "SD-" + year;//出库详情
		String nameIn = "IS-" + year;	//入库
		String nameInDet = "ID-" + year;//入库详情
		String nameStore = "ST-" + year;	//库存


		String nOut = yzrMedOutstockDAO.findMaxId(nameOut);
		//出库id
		YzrEntityService entityService = new YzrEntityService();
		String outstockId = entityService.getId(nameOut, nOut);
		
		YzrMedDraw draw = yrMedDrawDAO.findOne(drawId);
		
		//出库：出库编号，药品提领单号,出库类型（调拨出库，提领出库），仓库编号，出库到，出库人，出库时间
		YzrMedOutstock outstock =  new YzrMedOutstock();
		outstock.setMedOutstockId(outstockId);
		outstock.setMedOutstockMedDrawId(drawId);
		outstock.setMedOutstockKind(kind);
		outstock.setMedOutstockStoreId(draw.getMedDrawStoreId());
		outstock.setMedOutstockWhere(draw.getMedDrawPharmacyId());
		outstock.setMedOutstockPerson(new BigDecimal(ckr));
		outstock.setMedOutstockTime(new Date());
		yzrMedOutstockDAO.save(outstock);
		
		List<YzrMedDrawDet> drawDetList = yzrMedDrawDetDAO.findDrawDetByDrawId2(drawId);
		for(YzrMedDrawDet drawDet: drawDetList){
			//出库详情：出库详情编号，出库编号，药品编号，药品名称，批号，规格，单位,单价，数量
			YzrMedOutstockDet outDet = new YzrMedOutstockDet();
			String nOutDet = yzrMedOutstockDetDAO.findMaxId(nameOutdet);
			outDet.setMedOutstockDetId(entityService.getId(nameOutdet, nOutDet));
			outDet.setMedChukuId(outstockId);
			outDet.setMedOutstockDetMedId(drawDet.getMedDrawDetMedId());
			outDet.setMedOutstockDetMedName(drawDet.getMedDrawDetMedName());
			outDet.setMedOutstockDetBatchnumber(drawDet.getMedDrawDetBatchnumber());
			outDet.setMedOutstockDetGuige(drawDet.getMedDrawDetGuige());
			outDet.setMedOutstockDetUnit(drawDet.getMedDrawDetUnit());
			outDet.setMedOutstockDetPrice(drawDet.getMedDrawDetPrice());
			outDet.setMedOutstockDetNumber(drawDet.getMedDrawDetNumber());
			yzrMedOutstockDetDAO.save(outDet);
		}
		//添加入库和入库详情
		//入库：入库记录编号，提领单号，入库时间，负责人，药房（入的是那个药房）
		YzrPharInstock instock = new YzrPharInstock();
		
		String nIn = yzrPharInstockDAO.findMaxId(nameIn);
		String instockId = entityService.getId(nameIn, nIn);
		
		instock.setPharInstockId(instockId);
		instock.setPharInstockMedDrawId(drawId);
		instock.setPharInstockTime(new Date());
		instock.setPharInstockFuzeren(new BigDecimal(tlr));
		instock.setPharInstockPharmacyId(draw.getMedDrawPharmacyId());
		yzrPharInstockDAO.save(instock);
		
		//入库详情：入库详情编号，入库编号，药品编号，药品名称，批号，规格，单位,单价，数量
		for(YzrMedDrawDet drawDet: drawDetList){
			YzrPharInstockDet instockDet = new YzrPharInstockDet();
			String nInDet = yzrPharInstockDetDAO.findMaxId(nameInDet);
			instockDet.setPharInstockDetId(entityService.getId(nameInDet, nInDet));
			instockDet.setPharMedRukuId(instockId);
			instockDet.setPharInstockDetMedId(drawDet.getMedDrawDetMedId());
			instockDet.setPharInstockDetMedName(drawDet.getMedDrawDetMedName());
			instockDet.setPharInstockDetBatchnumber(drawDet.getMedDrawDetBatchnumber());
			instockDet.setPharInstockDetGuige(drawDet.getMedDrawDetGuige());
			instockDet.setPharInstockDetUnit(drawDet.getMedDrawDetUnit());
			instockDet.setPharInstockDetPrice(drawDet.getMedDrawDetPrice());
			instockDet.setPharInstockDetNumber(drawDet.getMedDrawDetNumber());
			yzrPharInstockDetDAO.save(instockDet);
		}
		
		//修改提领状态和修改库存数量
		draw.setMedDrawDrawState("已提领");
		draw.setMedDrawDrawPerson(new BigDecimal(tlr));
		draw.setMedDrawDrawTime(new Date());
		yrMedDrawDAO.save(draw);
		
		
		
		//添加药房库存				
		for(YzrMedDrawDet drawDet: drawDetList){
			
			String medId = drawDet.getMedDrawDetMedId();//药品编号
			String batchNumber = drawDet.getMedDrawDetBatchnumber();//批号
			YzrPharStock pharStockYzr = yzrPharStockDAO2.findByMedicine(medId, batchNumber);
			
			
			if(pharStockYzr == null){
				
				//药房库存:库存编号，药房编号，药品编号，药品名，批号，类型（中药，西药），规格，单位，单价，数量,售价
				YzrPharStock pharStock = new YzrPharStock();//药房库存
				String nStore = yzrPharStockDAO2.findMaxId(nameStore);
				pharStock.setPharStockId(entityService.getId(nameStore, nStore));
				pharStock.setPharStockStoreId(draw.getMedDrawPharmacyId());//药房
				pharStock.setPharStockMedId(drawDet.getMedDrawDetMedId());
				pharStock.setPharStockMedName(drawDet.getMedDrawDetMedName());
				pharStock.setPharStockBatchnumber(drawDet.getMedDrawDetBatchnumber());
				YzrMedicine med = yzrMedicineDAO.findOne(drawDet.getMedDrawDetMedId());
				pharStock.setPharStockMedKind(med.getMedKind());
				pharStock.setPharStockGuige(drawDet.getMedDrawDetGuige());
				pharStock.setPharStockUnit(drawDet.getMedDrawDetUnit());
				pharStock.setPharStockPrice(drawDet.getMedDrawDetPrice());
				pharStock.setPharStockMedNumber(drawDet.getMedDrawDetNumber());
				
				BigDecimal b1 = drawDet.getMedDrawDetPrice();
				BigDecimal b2 = new BigDecimal("1.5");
				
				pharStock.setMaiMoney(b1.multiply(b2));//售价
				yzrPharStockDAO2.save(pharStock);			
			}else{
				pharStockYzr.setPharStockMedNumber(pharStockYzr.getPharStockMedNumber().add(drawDet.getMedDrawDetNumber()));
				yzrPharStockDAO2.save(pharStockYzr);
			}
					
			
			//修改药库库存			
			YzrMedStock medStock = yzrMedStockDAO.findByMedicine(medId, batchNumber);
			if(medStock != null){
				medStock.setMedStockNumber(medStock.getMedStockNumber().subtract(drawDet.getMedDrawDetNumber()));
			}
			yzrMedStockDAO.save(medStock);		
			
		}
	}
	
	
	
	
	
	/**
	 * 格式化日期
	 * @return
	 */
	public static String getNowDate() {
		  Date currentTime = new Date();
		  SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		  String dateString = formatter.format(currentTime);
		  return dateString;
	}
}
